#! -*- coding:utf-8 -*-
import logging
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from common.utils.telegram import send_text_msg_tele
from common.bankcard.model import BankCard, BANKCARD_STATUS
from common.cache import redis_cache
from common.order import db as order_db

_LOGGER = logging.getLogger('worker')

WARN_TG_GROUP_ID = -353461302


# 五分钟一次 告警待处理事项
# cd /home/ubuntu/af-env/hydra;/home/ubuntu/af-env/bin/python manage.py warn_bot
class Command(BaseCommand):

    def balance_warning(self, item):
        if item.balance < item.daily_recharge_limit:
            return
        msg = u'银行卡余额到达限额\n'
        msg += u'名称:' + unicode(item.name) + u'\n'
        msg += u'持卡人:' + unicode(item.account_holder) + u'\n'
        msg += u'银行:' + unicode(item.bank) + u'\n'
        msg += u'当前余额:' + unicode(item.balance) + u'\n'
        msg += u'告警余额:' + unicode(item.daily_recharge_limit) + u'\n'
        send_text_msg_tele(WARN_TG_GROUP_ID, msg)

    def offline_warning(self, item):
        if item.status == BANKCARD_STATUS.ENABLE and not redis_cache.get_bankcard_online_status(item.name):
            msg = u'开启状态银行卡客户端离线\n'
            msg += u'名称:' + unicode(item.name) + u'\n'
            send_text_msg_tele(WARN_TG_GROUP_ID, msg)

    def nopay_warning(self, item):
        m = 15
        ttt = datetime.utcnow() + timedelta(minutes=-m)
        total_count, success_count = order_db.get_card_late_order_status(item.name, m)
        if item.status == BANKCARD_STATUS.ENABLE and redis_cache.get_bankcard_online_status(
                item.name) and item.updated_at < ttt and success_count == 0 and total_count > 0:
            msg = u'工作银行卡: %s, %s分钟没有成功支付订单，下单数：%s' % (item.name, m, total_count)
            send_text_msg_tele(WARN_TG_GROUP_ID, msg)

    def handle(self, **options):
        print 'start'
        items = BankCard.query.all()
        for item in items:
            # 测试卡不发告警
            if item.name in ['CCB001', 'CCB002']:
                continue
            self.balance_warning(item)
            # self.offline_warning(item)
            self.nopay_warning(item)
        print 'end'
